#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include <libpmemblk.h>

#define POOL_SIZE ((size_t)(1024 * 1024 * 1024))  /* size of the pmemblk pool -- 1 GB */
#define ELEMENT_SIZE 1024  /* size of each element in the pmem pool */

int main(int argc, char *argv[])
{
	    const char path[] = "/mnt/pmem1/sungan/test_pmem/test_blk";
	        char buf[ELEMENT_SIZE];
		    char rcv[ELEMENT_SIZE];

		        /* create the pmemblk pool or open it if it already exists */
		        PMEMblkpool *pbp = pmemblk_create(path, ELEMENT_SIZE, POOL_SIZE, 0666);

			    if (pbp == NULL)
				            pbp = pmemblk_open(path, ELEMENT_SIZE);

			        if (pbp == NULL) {
					        perror(path);
						        exit(1);
							    }

				    /* how many elements fit into the file? */
				    size_t nelements = pmemblk_nblock(pbp);
				        printf("file holds %zu elements\n", nelements);

					    /* store a block at index 5 */
					    strcpy(buf, "hello, world");
					        printf("buf: %s\n", buf);
						    if (pmemblk_write(pbp, buf, 0) < 0 ||
								            pmemblk_write(pbp, buf, 5) < 0 ||
									            pmemblk_write(pbp, buf, 6) < 0) {
							            perror("pmemblk_write");
								            exit(1);
									        }

						        /* read the block at index 5 */
						        if (pmemblk_read(pbp, rcv, 5) < 0) {
								        perror("pmemblk_read");
									        exit(1);
										    }
							    printf("rcv: %s\n", rcv);

							        /* read the block at index 10 (reads as zeros initially) */
							        if (pmemblk_read(pbp, rcv, 10) < 0) {
									        perror("pmemblk_read");
										        exit(1);
											    }
								    printf("rcv: %s\n", rcv);

								        /* zero out the block at index 5 */
								        if (pmemblk_set_zero(pbp, 5) < 0) {
										        perror("pmemblk_set_zero");
											        exit(1);
												    }

									    /* read the block at index 5 */
									    if (pmemblk_read(pbp, rcv, 5) < 0) {
										            perror("pmemblk_read");
											            exit(1);
												        }
									        printf("rcv: %s\n", rcv);

										    pmemblk_close(pbp);

										        return 0;
}
